interface MenuItem {
  id: number;
  path: string;
  name: string;
  redirect: string;
  meta: string;
  parentId: number;
  active: number;
  children?: MenuItem[];
}

export default function transformMenuData(menuList: MenuItem[]): MenuItem[] {
  // 先将 meta 字段的 JSON 字符串转换为对象，并添加错误处理
  const parsedMenuList = menuList.map((item) => {
    try {
      return {
        ...item,
        meta: JSON.parse(item.meta),
      };
    } catch (error) {
      console.error(
        `解析 meta 字段失败，id: ${item.id}, meta: ${item.meta}`,
        error,
      );
      return {
        ...item,
        meta: {}, // 解析失败时，将 meta 设为空对象
      };
    }
  });

  // 使用 Map 存储每个菜单项，方便快速查找
  const menuMap = new Map<number, MenuItem>();
  parsedMenuList.forEach((item) => {
    menuMap.set(item.id, { ...item, children: [] });
  });

  const rootMenus: MenuItem[] = [];

  parsedMenuList.forEach((item) => {
    const menuItem = menuMap.get(item.id)!;
    if (item.parentId === 0) {
      rootMenus.push(menuItem);
    } else {
      const parent = menuMap.get(item.parentId);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(menuItem);
      }
    }
  });

  return rootMenus;
}
